<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.min.js"></script>
  </head>
  <body>
    <button id="btn">自动取消请求接口</button>

    <script>
      const service = axios.create({
        timeout: 30000,
        retry: 1, // 请求次数
        baseURL: 'http://localhost:8080',
      });
      let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
      let cancelToken = axios.CancelToken;
      let removePending = (ever) => {
        for (let p in pending) {
          if (pending[p].u === ever.url + '&' + ever.method) {
            pending[p].f(); //执行取消操作
            pending.splice(p, 1); //把这条记录从数组中移除
          }
        }
      };
      service.interceptors.request.use(
        (config) => {
          removePending(config);
          config.cancelToken = new cancelToken((c) => {
            // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
            pending.push({ u: config.url + '&' + config.method, f: c });
          });
          return config;
        },
        (error) => {}
      );

      service.interceptors.response.use(
        (res) => {
          removePending(res.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
          return res;
        },
        (err) => {
          console.log(err);
        }
      );
      btn.addEventListener(
        'click',
        function () {
          service({
            url: '/testCancel',
            method: 'GET',
          });
        },
        false
      );
    </script>
  </body>
</html>
